<template>
  <el-row class="user-info-form" type="flex" justify="center" v-loading="loading">
    <el-col>
      <el-form label-position="top" :model="editForm" :rules="editFormRules" ref="editForm" @submit.native.prevent>
        <input type="hidden" v-model="editForm.id" />
        <el-form-item label="公告名称：" prop="name">
          <el-input v-model.trim="editForm.name" auto-complete="off" placeholder="请输入公告名称"></el-input>
        </el-form-item>
        <el-form-item label="时间范围" required>
          <el-col :span="11">
            <el-form-item prop="beginTimeStr">
              <el-form-item>
                <el-date-picker
                  v-model="editForm.beginTimeStr"
                  value-format="yyyy-MM-dd 00:00:00"
                  style="width: 100%;"
                  type="date"
                  placeholder="开始日期"
                  :picker-options="startTimePickerOptions"
                ></el-date-picker>
              </el-form-item>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item prop="endTimeStr">
              <el-date-picker
                v-model="editForm.endTimeStr"
                value-format="yyyy-MM-dd 23:59:59"
                style="width: 100%;"
                type="date"
                placeholder="结束日期"
                :picker-options="endTimePickerOptions"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="首页缩略图图片：" prop="thumbnailImg">
          <el-upload
            :action="QINIUUPLOADURL"
            :multiple="true"
            ref="upload"
            list-type="picture-card"
            :data="qiniuData"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemovePic"
            :on-error="handleError"
            :before-upload="beforeAvatarUpload"
            :on-preview="$imgPreview"
            :file-list="qiniuData.fileList"
            accept="image/gif, image/jpeg, image/jpg, image/bmp, image/png"
          >
            <div slot="tip" class="el-upload__tip">请上传680*320尺寸的图片</div>
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="公告内容类型：">
          <el-select filterable v-model="editForm.contentType">
            <el-option label="图片" value="1"></el-option>
            <el-option label="图文" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公告详情图片：" v-show="editForm.contentType==1" prop="detailImg">
          <el-upload
            :action="QINIUUPLOADURL"
            :multiple="true"
            ref="upload1"
            list-type="picture-card"
            :data="qiniuData1"
            :on-success="handleAvatarSuccess1"
            :on-remove="handleRemovePic1"
            :on-error="handleError"
            :before-upload="beforeAvatarUpload1"
            :on-preview="$imgPreview"
            :file-list="qiniuData1.fileList"
            accept="image/gif, image/jpeg, image/jpg, image/bmp, image/png"
          >
            <div slot="tip" class="el-upload__tip">请上传高清图片，以纵图为佳</div>
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="公告详情：" v-show="editForm.contentType==2" prop="content">
          <quill-editor
            ref="myQuillEditor"
            v-model="editForm.content"
            :options="util.intEditorOptions()"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
          ></quill-editor>
          <!-- 文件上传input 将它隐藏-->
          <el-upload
            :action="QINIUUPLOADURL"
            :before-upload="beforeAvatarUploadEditor"
            :data="qiniuDataEditor"
            :on-success="handleAvatarSuccessEditor"
            ref="uploadEditor"
            style="display:none"
          >
            <el-button size="small" type="primary" id="imgInput">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button @click="closeDialog()">取消</el-button>
          <el-button type="primary" @click="saveEdit('editForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
import util from '@/utils/util'
import { qnToken } from '@/api/api'
import { saveNotice } from '@/api/notice'

export default {
  name: 'PointTypeMaintain',
  props: {
    editInfo: {
      type: Object,
      required: false,
    },
    closeDialog: {
      type: Function,
      required: true,
    },
  },
  // 页面加载后执行 为编辑器的图片图标和视频图标绑定点击事件
  mounted() {
    // 为图片ICON绑定事件  getModule 为编辑器的内部属性
    this.$refs.myQuillEditor.quill
      .getModule('toolbar')
      .addHandler('image', this.imgHandler)
    this.$refs.myQuillEditor.quill
      .getModule('toolbar')
      .addHandler('video', this.videoHandler) // 为视频ICON绑定事件
  },
  data() {
    let that = this
    // 检测缩略图
    var checkThumbnailImg = (rule, value, callback) => {
      var data = that.qiniuData.fileList
      if (data.length < 1) {
        callback(new Error('请选择首页缩虐图图片'))
      } else {
        callback()
      }
    }
    // 检测公告详情图片
    var checkDetailImg = (rule, value, callback) => {
      var data = that.qiniuData1.fileList
      if (data.length < 1 && this.editForm.contentType == 1) {
        callback(new Error('请选择公告详情图片'))
      } else {
        callback()
      }
    }
    // 检测公告详情
    var checkContent = (rule, value, callback) => {
      var data = that.editForm.content
      if (data == '' && this.editForm.contentType == 2) {
        callback(new Error('请输入公告详情'))
      } else {
        callback()
      }
    }
    return {
      startTimePickerOptions: {
        disabledDate: (time) => {
          if (that.editForm.endTimeStr && that.editForm.endTimeStr != '') {
            let endDate = new Date(that.editForm.endTimeStr)
            endDate = new Date(endDate.setDate(endDate.getDate()))
            return time > endDate
          } else {
            return false
          }
        },
      },
      endTimePickerOptions: {
        disabledDate: (time) => {
          if (that.editForm.beginTimeStr && that.editForm.beginTimeStr != '') {
            let startDate = new Date(that.editForm.beginTimeStr)
            startDate = new Date(startDate.setDate(startDate.getDate()))
            return time < startDate
          } else {
            return false
          }
        },
      },
      qiniuData: {
        //上传图片携带的参数
        token: '',
        key: '',
        fileList: [],
      },
      qiniuData1: {
        //上传图片携带的参数
        token: '',
        key: '',
        fileList: [],
      },
      qiniuDataEditor: {
        //富文本编辑器相关
        token: '',
        key: '',
        fileList: [],
      },
      defaultImg: this.GLOBAL.defaultImg,
      util: util,
      loading: false,
      editForm: {
        id: '',
        name: '',
        orgId: this.$store.state.userinfo.org.id,
        beginTimeStr: '',
        endTimeStr: '',
        thumbnailImg: '',
        detailImg: '',
        contentType: '1',
        content: '', //富文本
        remark: '',
      },
      editFormRules: {
        name: [{ required: true, message: '请输入公告名称', trigger: 'blur' }],
        beginTimeStr: [
          {
            type: 'string',
            required: true,
            message: '请选择日期',
            trigger: 'change',
          },
        ],
        endTimeStr: [
          {
            type: 'string',
            required: true,
            message: '请选择日期',
            trigger: 'change',
          },
        ],
        thumbnailImg: [
          { required: true, validator: checkThumbnailImg, trigger: 'change' },
        ],
        detailImg: [
          { required: true, validator: checkDetailImg, trigger: 'change' },
        ],
        content: [{ required: true, validator: checkContent, trigger: 'blur' }],
      },
    }
  },
  created() {
    let infoObj = this.editInfo
    if (infoObj.id) {
      //编辑
      this.editForm.id = infoObj.id
      this.editForm.contentType = infoObj.contentType.toString()
      this.editForm.beginTimeStr = infoObj.beginTime
      this.editForm.endTimeStr = infoObj.endTime
      this.editForm.orgId = infoObj.orgId || this.$store.state.userinfo.org.id
      this.editForm.name = infoObj.name
      this.editForm.content = infoObj.content
      this.editForm.thumbnailImg = infoObj.thumbnailImg
      infoObj.thumbnailImg
        ? $.each(infoObj.thumbnailImg.split(','), (index, url) => {
            this.qiniuData.fileList.push({
              name: '首页缩略图图片' + index,
              url: url,
            })
          })
        : ''
      this.editForm.detailImg = infoObj.detailImg
      infoObj.detailImg
        ? $.each(infoObj.detailImg.split(','), (index, url) => {
            this.qiniuData1.fileList.push({
              name: '公告详情图片' + index,
              url: url,
            })
          })
        : ''
    }
    this.getToken() //获取token
  },
  methods: {
    getToken() {
      //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token = result.data
        this.qiniuData1.token = result.data
        this.qiniuDataEditor.token = result.data //富文本编辑器相关
      })
    },
    beforeAvatarUpload: function (file) {
      //重命名和校验
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      this.qiniuData.key = 'ilink_' + new Date().getTime() + fielType
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isJPG && !isPNG) {
        this.$message.error('图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('图片大小不能超过 20MB!')
        return false
      }
    },
    beforeAvatarUpload1: function (file) {
      //重命名和校验
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      this.qiniuData1.key = 'ilink_' + new Date().getTime() + fielType
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isJPG && !isPNG) {
        this.$message.error('图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('图片大小不能超过 20MB!')
        return false
      }
    },
    handleAvatarSuccess: function (res, file, fileList) {
      //上传成功
      this.qiniuData.fileList = fileList
    },
    handleAvatarSuccess1: function (res, file, fileList) {
      //上传成功
      this.qiniuData1.fileList = fileList
    },
    handleRemovePic: function (file, fileList) {
      //删除成功
      this.qiniuData.fileList = fileList
    },
    handleRemovePic1: function (file, fileList) {
      //删除成功
      this.qiniuData1.fileList = fileList
    },
    handleError: function (res) {
      this.$message({
        message: '上传失败',
        duration: 2000,
        type: 'warning',
      })
    },
    //--------------------BEGIN  富文本编辑器相关------------------------------//
    beforeAvatarUploadEditor: function (file) {
      //重命名和校验
      this.loading = true
      const suffix = file.name.split('.')
      const ext = suffix.splice(suffix.length - 1, 1)[0]
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      this.qiniuDataEditor.key = 'ilink_' + new Date().getTime() + fielType
    },
    handleAvatarSuccessEditor: function (res, file, fileList) {
      //上传成功
      this.loading = false
      let vm = this
      let url = QINIUUPLOADURL.indexOf('uploadFile')>-1? res.data:QINIUPATH+res.key
      if (url != null && url.length > 0) {
        // 将文件上传后的URL地址插入到编辑器文本中
        let value = url
        vm.qiniuDataEditor.fileList = vm.$refs.myQuillEditor.quill.getSelection()
        vm.$refs.myQuillEditor.quill.insertEmbed(
          vm.qiniuDataEditor.fileList !== null
            ? vm.qiniuDataEditor.fileList.index
            : 0,
          vm.uploadType,
          value
        ) // 调用编辑器的 insertEmbed 方法，插入URL
      } else {
        this.$message.error('上传失败')
      }
      this.$refs['uploadEditor'].clearFiles() // 插入成功后清除input的内容
    },
    // 点击图片ICON触发事件
    imgHandler(state) {
      this.addRange = this.$refs.myQuillEditor.quill.getSelection()
      if (state) {
        let fileInput = document.getElementById('imgInput')
        fileInput.click() // 加一个触发事件
      }
      this.uploadType = 'image'
    },
    // 点击视频ICON触发事件
    videoHandler(state) {
      this.addRange = this.$refs.myQuillEditor.quill.getSelection()
      if (state) {
        let fileInput = document.getElementById('imgInput')
        fileInput.click() // 加一个触发事件
      }
      this.uploadType = 'video'
    },
    // 编辑器光标离开 将编辑器内容发射给父组件
    onEditorBlur(editor) {
      this.$emit('getValue', this.editForm.content)
    },
    // 编辑器获得光标
    onEditorFocus(editor) {
      editor.enable(true) // 实现达到上限字符可删除
    },
    // 编辑器文本发生变化
    onEditorChange({ editor, html, text }) {
      let textLength = text.length
      if (textLength > 10000) {
        this.$message.error('最多输入10000个字符')
        editor.enable(false)
      }
      this.$emit('getValue', this.editForm.content)
    },
    // 清除编辑器内容
    callMethod() {
      this.editForm.content = ''
    },
    //--------------------END  富文本编辑器相关------------------------------//
    saveEdit(formName) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      that.$refs[formName].validate((valid) => {
        if (valid) {
          let parames = that.editForm
          parames.thumbnailImg = util.ilinkArrHandle
            .getqiniuPicUrlArr(this.qiniuData.fileList)
            .toString()
          parames.detailImg = util.ilinkArrHandle
            .getqiniuPicUrlArr(this.qiniuData1.fileList)
            .toString()
          saveNotice(parames).then((res) => {
            if (res.status === 200) {
              that.$message({
                message: '保存成功！',
                type: 'success',
              })
              that.closeDialog(true)
            } else {
              that.$message({
                message: res.info,
                type: 'warning',
              })
            }
          })
        } else {
          return false
        }
      })
    },
  },
}
</script>